package org.duiduo.common.tool.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * cmd命令工具类
 *
 * @author liangze
 * @date 2024/11/4 15:43
 */
@Slf4j
public class CommandUtil {

    /**
     * cmd命令处理
     *
     * @param cmdText cmd指令
     */
    public static void cmdHandler(String cmdText, Long timeout) {
        InputStream is = null;
        BufferedReader br = null;
        try {
            Process process = Runtime.getRuntime().exec(cmdText);
            is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "GBK");
            br = new BufferedReader(isr);

            log.info("cmd开始执行:{}", cmdText);
            new RunThread(process.getInputStream(), "INFO").start();
            new RunThread(process.getErrorStream(), "ERROR").start();
            process.waitFor(timeout, TimeUnit.SECONDS);
        } catch (IOException e) {
            log.warn("cmd命令执行IO异常:", e);
            throw new RuntimeException(e.getMessage());
        } catch (InterruptedException e) {
            log.warn("cmd命令执行中断异常: ", e);
            throw new RuntimeException(e.getMessage());
        } catch (Exception e) {
            log.warn("cmd命令执行出现异常: ", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(is);
        }
    }

    @Slf4j
    static class RunThread extends Thread {
        InputStream is;
        String printType;

        RunThread(InputStream is, String printType) {
            this.is = is;
            this.printType = printType;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is, "GBK");
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    log.info(printType + ">" + line);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                log.warn("cmd命令执行获取日志失败:", ioe);
            }
        }
    }

}
